<template>
  <uni-forms ref="medicalForm" label-position="top">
    <uni-title type="h2" title="企业信息录入" align="center"></uni-title>

    <!-- 经营企业信息 -->
    <uni-forms-item label="经营企业名称" label-width="130" required>
      <uni-easyinput
        :value="formData.operatorName"
        @input="updateField('operatorName', $event)"
        placeholder="请输入经营企业名称"
      />
    </uni-forms-item>

    <uni-forms-item label="经营场所" required>
      <uni-easyinput
        :value="formData.operatorPlace"
        @input="updateField('operatorPlace', $event)"
        placeholder="请输入经营场所"
      />
    </uni-forms-item>

    <uni-forms-item label="仓库地址" required>
      <uni-easyinput
        :value="formData.address"
        @input="updateField('address', $event)"
        placeholder="请输入仓库地址"
      />
    </uni-forms-item>

    <!-- 经营方式选择 -->
    <uni-forms-item label="经营方式" required>
      <uni-data-select
        :value="formData.modeOfOperation"
        :localdata="operationOptions"
        @change="val => updateField('modeOfOperation', val)"
      />
    </uni-forms-item>

    <!-- 经营范围选择 -->
    <uni-forms-item label-width="130px" label="2002版经营范围" required>
      <multi-select-popup
        v-model="formData.workLayout2002List"
        :options="options2022"
        title="选择经营范围"
        placeholder="点击选择"
		 @update:labels="handleLabelsUpdate"
        :max-display="15"
      />
    </uni-forms-item>

    <uni-forms-item label-width="130px" label="2017版经营范围" required>
      <multi-select-popup
        v-model="formData.workLayout2017List"
        :options="options2017"
        title="选择经营范围"
        placeholder="点击选择"
		 @update:labels="handleLabelsUpdat2"
        :max-display="15"
      />
    </uni-forms-item>

    <!-- 负责人信息 -->
    <uni-forms-item label="法人姓名" required>
      <uni-easyinput
        :value="formData.legalPersonName"
        @input="updateField('legalPersonName', $event)"
        placeholder="请输入法人姓名"
      />
    </uni-forms-item>

    <uni-forms-item label="法人证件" required>
      <uni-easyinput
        :value="formData.leaglCertNo"
        @input="updateField('leaglCertNo', $event)"
        placeholder="请输入法人证件"
      />
    </uni-forms-item>

    <uni-forms-item label-width="130px" label="企业负责人姓名" required>
      <uni-easyinput
        :value="formData.enterpriseManagerName"
        @input="updateField('enterpriseManagerName', $event)"
        placeholder="请输入企业负责人姓名"
      />
    </uni-forms-item>

    <uni-forms-item label-width="130px" label="企业负责人证件" required>
      <view class="flex-container">
        <uni-easyinput
          :value="formData.enterpriseManagerCertNo"
          @input="updateField('enterpriseManagerCertNo', $event)"
          placeholder="请输入企业负责人证件"
          class="input-field"
        />
      <!-- 正确应该绑定到处理验证的方法 -->
      <button class="verify-button" @click="handleVerify('enterprise')">身份验证</button>
      </view>
    </uni-forms-item>

    <uni-forms-item label-width="130px" label="质量负责人姓名" required>
      <uni-easyinput
        :value="formData.qualityManagerName"
        @input="updateField('qualityManagerName', $event)"
        placeholder="请输入质量负责人姓名"
      />
    </uni-forms-item>

    <uni-forms-item label-width="130px" label="质量负责人证件" required>
      <view class="flex-container">
        <uni-easyinput
          :value="formData.qualityManagerCertNo"
          @input="updateField('qualityManagerCertNo', $event)"
          placeholder="请输入质量负责人证件"
          class="input-field"
        />
       <!-- 正确应该绑定到处理验证的方法 -->
       <button class="verify-button" @click="handleVerify('quality')">身份验证</button>
      </view>
    </uni-forms-item>
	
	<!-- 身份验证弹窗 -->
	    <uni-popup ref="verifyPopup" type="center" :is-mask-click="false">
	      <view class="verify-dialog">
	        <view class="dialog-header">
	          <text class="title">负责人身份验证记录</text>
	        </view>
	        <text style="margin:15px;font-size:17px;">
	          根据相关法规规定，同一人禁止兼任一家或多家医疗器械企业的企业负责人/质量负责人...
	        </text>
	        <view class="table-container">
	          <uni-table border stripe empty-text="暂无验证记录">
	            <uni-tr style="background-color:#e9f1fe">
	              <uni-th width="15%" align="center">姓名</uni-th>
	              <uni-th width="25%" align="center">证件号</uni-th>
	              <uni-th width="25%" align="center">所属企业</uni-th>
	              <uni-th width="15%" align="center">职位</uni-th>
	              <uni-th width="10%" align="center">记录时间</uni-th>
	            </uni-tr>
	            <uni-tr v-for="(item,index) in verifyRecords" :key="index">
	              <uni-td align="center">{{ item.name }}</uni-td>
	              <uni-td align="center">{{ item.idNumber }}</uni-td>
	              <uni-td align="center">{{ item.company }}</uni-td>
	              <uni-td align="center">{{ item.position }}</uni-td>
	              <uni-td align="center">{{ item.time }}</uni-td>
	            </uni-tr>
	          </uni-table>
	        </view>
	        <view class="dialog-footer">
	          <button class="cancel-btn" @click="closeVerify">关闭</button>
	        </view>
	      </view>
	    </uni-popup>
  </uni-forms>
  
  
</template>

<script>
	import { checkCertNo } from '@/api/order'

export default {
  props: {
    // 表单数据对象
    formData: {
      type: Object,
      default: () => ({
        operatorName: '',
        operatorPlace: '',
        address: '',
        modeOfOperation: '',
        workLayout2002List: [],
		workLayout2002Item:'',
        workLayout2017List: [],
		workLayout2017Item:'',
        legalPersonName: '',
        leaglCertNo: '',
        enterpriseManagerName: '',
        enterpriseManagerCertNo: '',
        qualityManagerName: '',
        qualityManagerCertNo: '',
		
      })
    },
    // 下拉选项数据
    options2022: {
      type: Array,
      default: () => []
    },
    options2017: {
      type: Array,
      default: () => []
    },
    operationOptions: {
      type: Array,
      default: () => []
    }
  },
data() {
    return {
      verifyRecords: [],
      currentVerifyType: null // enterprise/quality
    }
  },
  methods: {
   handleLabelsUpdate(labels) {
       console.log('标签字符串:', labels)
       this.formData.workLayout2002Item = labels
     },
	 handleLabelsUpdat2(labels) {
	     console.log('标签字符串:', labels)
	     this.formData.workLayout2017Item = labels
	   },
   updateField(field, value) {
       // 只传递变化的字段
       this.$emit('update', { 
         [field]: value // ✅ 仅传递变化的键值对
       })
     },

  
    // 表单验证方法（供父组件调用）
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.medicalForm.validate().then(res => {
          resolve(true)
        }).catch(err => {
          console.log('验证失败:', err)
          reject(false)
        })
      })
    },
	 // 处理身份验证
	    async handleVerify(type) {
	      this.currentVerifyType = type
	      const certNo = this.formData[`${type}ManagerCertNo`]
	
	      if (!certNo?.trim()) {
	        return uni.showToast({
	          title: `请先输入${this.getPositionName(type)}证件号`,
	          icon: 'none'
	        })
	      }
	
	      try {
	        const res = await checkCertNo({
	          enterpriseManagerCertNo: certNo
	        })
	
	        if (res.code === 0) {
	          this.verifyRecords = this.formatRecords(res.data)
	          this.$refs.verifyPopup.open()
	        }
	      } catch (error) {
	        uni.showToast({
	          title: '验证请求失败，请稍后重试',
	          icon: 'none'
	        })
	      }
	    },
		 // 格式化验证记录
		    formatRecords(data) {
		      return data.map(item => ({
		        name: item.qualityManagerName || '',
		        idNumber: item.enterpriseManagerCertNo || '',
		        company: item.operatorName || '',
		        position: item.legalPersonName || '',
		        time: item.createDate?.split(' ')[0] || ''
		      }))
		    }, // 获取职位名称
    getPositionName(type) {
      return {
        enterprise: '企业负责人',
        quality: '质量负责人'
      }[type]
    },
	 // 关闭验证弹窗
	    closeVerify() {
	      this.$refs.verifyPopup.close()
	      this.verifyRecords = []
	    },
	
	
  }
}
</script>

<style scoped>
.flex-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-field {
  flex: 1;
  margin: 0;
}

.verify-button {
  height: 40px;
  min-width: 100px;
  padding: 0 15px;
  margin: 0;
  line-height: 40px;
  border-radius: 4px;
  background-color: #1aad19;
  color: white;
  border: none;
}

/* 保持与父组件一致的输入框样式 */
:deep(.uni-easyinput__content) {
  height: 40px;
  border-radius: 4px;
}

:deep(.uni-forms-item__label) {
  font-weight: 600;
  color: #333;
}
.verify-dialog {
  width: 90vw;
  background: #fff;
  border-radius: 12px;
  padding: 20px;
}

.dialog-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  text-align: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.table-container {
  max-height: 60vh;
  overflow-y: auto;
  margin: 15px 0;
}

.dialog-footer {
  text-align: center;
  padding-top: 15px;
}

.cancel-btn {
  background-color: #ff4d4f;
  color: white;
  border-radius: 20px;
  padding: 0 25px;
}

/* 深度样式调整 */
:deep(.uni-table-th) {
  background-color: #f0f7ff !important;
}

:deep(.uni-table-td) {
  padding: 8px !important;
}
</style>